package com.yiren.backstage.communication.thread;

import android.content.Context;

import com.google.gson.Gson;
import com.yiren.backstage.communication.analysis.GpsRmcDataAnalysis;
import com.yiren.backstage.communication.analysis.GyroDataAnalysis;
import com.yiren.backstage.communication.analysis.JxDataAnalysis;
import com.yiren.backstage.communication.analysis.KsxtDataAnalysis;
import com.yiren.backstage.communication.analysis.MpDataAnalysis;
import com.yiren.backstage.communication.analysis.PublicDeviceAnalysis;
import com.yiren.backstage.communication.api.I4GCommunication;
import com.yiren.backstage.communication.api.impl.Public4GCommunicationApiImpl;
import com.yiren.backstage.communication.services.AbstractPortService;
import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.currency.bean.GyroData;
import com.yiren.backstage.currency.constant.DateTimeConstant;
import com.yiren.backstage.currency.constant.SignalGConstant;

import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Time:2021/12/23 17:54
 * Author:xiaozan
 * Description:读取数据线程
 */
public class ReadDataThread extends Thread {

    private Context context;
    private AbstractPortService abstractPortService;
    private byte[] data;
    private StringBuffer strLine;
    private String line;
    private BufferedReader bufferedReader;
    private GyroDataAnalysis gyroDataAnalysis;
    private JxDataAnalysis jxDataAnalysis;
    private MpDataAnalysis mpDataAnalysis;
    private GpsRmcDataAnalysis gpsRmcDataAnalysis;
    private KsxtDataAnalysis ksxtDataAnalysis;
    private PublicDeviceAnalysis publicDeviceAnalysis;
    private I4GCommunication i4GCommunication;

    private Gson gs = new Gson();
    Map<String, String> map = new HashMap<String, String>();

    public ReadDataThread(Context context, AbstractPortService abstractPortService) {
        this.context = context;
        this.abstractPortService = abstractPortService;
        data = new byte[256];
        strLine = new StringBuffer();
        jxDataAnalysis = new JxDataAnalysis(context);
        mpDataAnalysis = new MpDataAnalysis(context);
        gyroDataAnalysis = new GyroDataAnalysis();

        gpsRmcDataAnalysis = new GpsRmcDataAnalysis(context);
        ksxtDataAnalysis = new KsxtDataAnalysis();
        publicDeviceAnalysis = new PublicDeviceAnalysis();
        i4GCommunication = new Public4GCommunicationApiImpl(context);
    }

    @Override
    public void run() {
        try {
            // 取得输入、输出流
            bufferedReader = new BufferedReader(new InputStreamReader(abstractPortService.getInputStream()));
        } catch (Exception e) {
            return;
        }
        while (true) {
            try {
                while ((line = bufferedReader.readLine()) != null) {
                    dataAnalysis(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
                try {
//                    abstractPortService.stop();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                line = null;
            }
        }
    }

    /**
     * 解析数据
     */
    private void dataAnalysis(String line) {
        if (null != line) {
            strLine.append(line);
        }
        if (countStr(strLine.toString(), "$") >= 2) {
            line = strLine.substring(0, strLine.indexOf("$", 1));
            abstractPortService.onReadData(line);
            DateTimeConstant.carMasterRetTime = System.currentTimeMillis();
            strLine = new StringBuffer(strLine.substring(strLine.indexOf("$", 1), strLine.length()));
            String jxConfig = LoadConfigApi.loadDeviceStudyConfig(context).getJxConfig();
            if (jxConfig!=null) {
                if (StringUtils.isNotEmpty(jxConfig)) {
                    map = gs.fromJson(jxConfig, map.getClass());
                }
            }
            if (line.contains("$<JX")) {
                jxDataAnalysis.dataAnalysis(line, map);
            }
            if (line.contains("$<MP")) {
                mpDataAnalysis.dataAnalysis(line);
                SignalGConstant.carMasterDataMP = line;
            }
            if (line.contains("$<GYRO")) {
                DateTimeConstant.angleRetTime = System.currentTimeMillis();
                GyroData.setReceiverInter(line);
                gyroDataAnalysis.dataAnalysis(line);
                gyroDataAnalysis.initCarMasterTelent(context);
            }
            if (line.contains("RMC")) {
                DateTimeConstant.gpsRetTime = System.currentTimeMillis();
                gpsRmcDataAnalysis.dataAnalysis(line);
            }
            if (line.contains("GGA")) {
                SignalGConstant.gpsGpgga = line;
                gpsRmcDataAnalysis.dataAnalysis(line);
            }
            if (line.contains("KSXT")) {
                SignalGConstant.cfGpsData = line;
                ksxtDataAnalysis.dataAnalysis(line);
            }
            SignalGConstant.allData = line;
        }
        if (null != line && (line.contains("RE_AUTH") || line.contains("RE_PARAM") || line.contains("RE_REBOOT") || line.contains("RE_UPDATE") || line.contains("RE_BBDCT") || line.contains("RE_ACDID") || line.contains("MP") || line.contains("A0") || line.contains("A1") || line.contains("A2") || line.contains("A3") || line.contains("51") || line.contains("52") || line.contains("41"))) {
            publicDeviceAnalysis.dataAnalysis(line);
        }
        if (null != line && ((line.contains("AT+READ=YES") || line.contains("AT+MODE=CFG_4G") || line.contains("AT+CFG_END") || line.contains("AT+READ=NO") || line.contains("ICCID") || line.contains("REGDT") || line.contains("VER:")))) {
            SignalGConstant.allData = line;
            i4GCommunication.analysisReceiver(line);
        }
        if (null != line && line.contains("$AT+YTJ = OK")) { //返回$AT+YTJ = OK\r\n则说明是一体机
            SignalGConstant.ISYITIJI = true;
        }
        if (null != line && (line.contains("$<JX"))) {
            if (line.contains("$<JXS")) {
                RTKConnection.setIsNonFourG(true);
            } else {
                RTKConnection.setIsNonFourG(false);
            }
        }
    }

    /**
     * 判断字符串中某个字符存在的个数
     *
     * @param str1 完整字符串
     * @param str2 要统计匹配个数的字符
     * @return
     */
    public static int countStr(String str1, String str2) {
        int count = 0;
        if (str1.indexOf(str2) == -1) {
            return 0;
        }
        while (str1.indexOf(str2) != -1) {
            count++;
            str1 = str1.substring(str1.indexOf(str2) + str2.length());
        }
        return count;
    }
}
